package wsz.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import wsz.rpc.common.RpcRequest;
import wsz.rpc.common.RpcResponse;
import wsz.rpc.consumer.client.RpcClient;

import java.lang.reflect.Proxy;
import java.util.*;

/**
 * 客户端连接代理类
 * @author wsz
 * @date 2021/12/01 18:29
 **/
@Component
public class RpcClientProxy {

    @Value("#{'${netty.server}'.split(',')}")
    private List<String> clientSourceList = new ArrayList<>();

    /**
     * 1.缓存netty连接通道
     * 2.实现随机负载均衡
     */
    private List<RpcClient> clientList = new ArrayList<>();
    private Random random = new Random();
    private RpcClient randomClient() {
        return clientList.get(random.nextInt(clientList.size()));
    }
    private void initServers() {
        if (clientList.isEmpty()) {
            for (String clientStr : clientSourceList) {
                String[] split = clientStr.split(":");
                clientList.add(new RpcClient(split[0], Integer.valueOf(split[1])));
            }
        }
    }

    /**
     * 缓存被代理类
     */
    private Map<String, Object> proxyMap = new HashMap<>();

    /**
     * 代理类中进行rpc调用
     * @param serviceClass
     * @return
     */
    public Object createProxy(Class serviceClass) {
        initServers();
        String className = serviceClass.getName();
        if (!proxyMap.containsKey(className)) {
            Object proxyTarget =  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class[]{serviceClass},
                    (proxy, method, args) -> {
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        // TODO 负载均衡
                        RpcClient rpcClient = randomClient();
                        try {
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));

                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            Object result = rpcResponse.getResult();
                            if (result == null) {
                                return null;
                            }
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception ex) {
                            throw ex;
                        }
                    });
            proxyMap.put(className, proxyTarget);
        }
        return proxyMap.get(className);
    }
}
